package com.ibm.moa.outmail.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.os.AsyncTask;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.ibm.moa.outmail.MailApplication;
import com.ibm.moa.outmail.R;

public class DownLoadDBTask extends AsyncTask<Object, Integer, File> {
	private ProgressDialog mProgressDialog;
	private Context context;
	private String fileName;
	private File outFile = null;
	public DownLoadDBTask(Context context){
		this.context = context;
	}
	
	protected File doInBackground(Object... views) {
		String urlStr =  (String) views[0];
		fileName = (String) views[1];
		
//		String dbName = ""; 
//		int index = urlStr.lastIndexOf("/");
//		if(index != -1){
//			dbName = urlStr.substring(index+1);
//		}
		int count = 0;
		int fileSize = 0;
		try {
			URL apkUrl = new URL(urlStr);
			HttpURLConnection http = (HttpURLConnection) apkUrl.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			http.setRequestProperty("Accept-Language", "zh-CN");
			http.setRequestProperty("Referer", apkUrl.toString());
			http.setRequestProperty("Charset", "UTF-8");
			http.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			http.setRequestProperty("Connection", "Keep-Alive");
			if(http.getResponseCode() == 200){
				fileSize = http.getContentLength();
				if (fileSize <= 0) {
					return null;
				}
				mProgressDialog.setMax(fileSize);
				InputStream inStream = http.getInputStream();
				String contentEncodingStr = http.getContentEncoding();
				Log.i("lgs", "contentEncodingStr="+contentEncodingStr);
				File sdCardDir = new File(MailApplication.fileSaveDir);
				sdCardDir.mkdirs();
				outFile = new File(sdCardDir , fileName);
				if("gzip".equalsIgnoreCase(contentEncodingStr)) {
					GZIPInputStream inputGzipInputStream = new GZIPInputStream(inStream);
					byte[] buffer = new byte[1024];
					int len = -1;
					FileOutputStream fos=new FileOutputStream(outFile);
					while( (len = inputGzipInputStream.read(buffer)) != -1){
						fos.write(buffer, 0, len);
						count += len;
						publishProgress(count);
					}
					fos.close();
					inStream.close();
					inputGzipInputStream.close();
				} else {
					byte[] buffer = new byte[1024];
					int len = -1;
					FileOutputStream fos=new FileOutputStream(outFile);
					while( (len = inStream.read(buffer)) != -1){
						fos.write(buffer, 0, len);
						count += len;
						publishProgress(count);
					}
					fos.close();
					inStream.close();
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return outFile;
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) {
		mProgressDialog.setProgress(values[0]);
		super.onProgressUpdate(values);
	}

	@Override
	protected void onCancelled() {
		if(mProgressDialog != null){
			mProgressDialog.dismiss();
		}
		this.cancel(true);
		super.onCancelled();
	}

	@Override
	protected void onPreExecute() {
		try{
			if(context != null){
				mProgressDialog = new ProgressDialog(context);
		        mProgressDialog.setIcon(R.drawable.icon);
		        mProgressDialog.setTitle("下载数据中");
		        mProgressDialog.setOnKeyListener(new OnKeyListener() {
					
					@Override
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						if(keyCode == KeyEvent.KEYCODE_BACK) {
							
							onCancelled();
						}
						return false;
					}
				});
		        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		        mProgressDialog.setButton("取消", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            	onCancelled();
		            }
		        });
		        
	        	mProgressDialog.show();
		        
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		super.onPreExecute();
	}

	protected void onPostExecute(File apkUrl) {
		try{
			if(mProgressDialog != null){
				mProgressDialog.dismiss();
			}
			if(apkUrl != null && context != null){
				AlertDialog.Builder dialog= new AlertDialog.Builder(context)
				.setTitle("下载完毕")
				.setMessage(fileName+"已下载到"+MailApplication.fileSaveDir+"目录中，是否打开？")
				.setPositiveButton("确定", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try{
							OpenFiles.startFile(context, outFile);
						}catch (Exception e) {
							Toast.makeText(context, "无法打开此文件，请您到"+MailApplication.fileSaveDir+"目录中手动打开", Toast.LENGTH_SHORT).show();
						}
						dialog.dismiss();
					}
				})
				.setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				
				dialog.show();
			}else if(context != null){
				Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	public void cancleTask(){
	}
}